package com.okilo.online.app.act

import android.Manifest
import android.content.Context
import android.content.Intent
import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.okilo.online.app.R
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.databinding.OkiloActPermListBinding
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.tools.OkiloDensityUtil
import com.okilo.online.app.tools.OkiloTitleBarUtil
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.decoration.LinearSpacingItemDecoration
import com.okilo.online.app.tools.helper.OkiloPermHp
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import com.okilo.online.app.apt.OkiloPermApt
import com.okilo.online.app.dialog.OkiloTipsDlog
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:04
 * @Annotation：权限
 */
class OkiloPermAct: OkiloComAct(), EasyPermissions.RationaleCallbacks {
    lateinit var binding: OkiloActPermListBinding

    private val PERMISSION_REQUEST_CODE : Int = 100;
    private var okiloPermApt: OkiloPermApt? = null

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, OkiloPermAct::class.java)
            context.startActivity(intent)
        }
    }

    override val pageName: String = "Permission_Page"

    override fun createOkiloContentView(): View {
        binding = OkiloActPermListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeOkiloViews() {
        OkiloTitleBarUtil.setStatusBarLightMode(this, true)
        isInterceptBack(true)
        getTitleBarManager()
            .setTitleBarVisibility(View.VISIBLE)
            .setTitle(getString(R.string.okilo_perm_title))
            .setBackButtonVisibility(View.INVISIBLE)
            .setRightButtonVisibility(View.VISIBLE)
        initOkiloPermListView()
        binding.okiloPermLayout.visibility = View.INVISIBLE
    }

    override fun setupOkiloEventListeners() {
        super.setupOkiloEventListeners()
        //拒绝
        binding.okiloPermButtonDeny.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS,-1)
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_DENY,packageName)

                sOkiloPermCallback(isGranted = false)
            }
        })
        //同意
        binding.okiloPermButtonAgree.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_AGREE,packageName)
                if (!binding.okiloPermCheckBox.isChecked){
                    sOkiloPermReasonDialog()
                    return
                }
                gOkiloPermAction()
            }
        })
    }

    override fun loadOkiloData() {
        gOkiloPermDataList()
    }

    //拦击系统返回键
    override fun onBackAction(){
        //系统返回，视为未操作
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS,0)
        sOkiloPermCallback(isGranted = false)
    }

    /**
     * 初始化权限列表
     */
    private fun initOkiloPermListView(){
        binding.okiloPermListView.setHasFixedSize(true)
        binding.okiloPermListView.isNestedScrollingEnabled = false
        binding.okiloPermListView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = OkiloDensityUtil.dp2px(16f)
        binding.okiloPermListView.addItemDecoration(
            LinearSpacingItemDecoration(
                topDecoration,
                topDecoration,
                topDecoration,
                topDecoration
            )
        )
        binding.okiloPermListView.layoutManager = LinearLayoutManager(this)
        okiloPermApt = OkiloPermApt(binding.okiloPermListView)
        binding.okiloPermListView.adapter = okiloPermApt
        binding.okiloPermListView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 执行跳转逻辑
     */
    fun sOkiloPermCallback(isGranted: Boolean){
        val intent = intent
        intent.putExtra("isGranted",isGranted)
        setResult(RESULT_OK,intent)
        finish()
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        OkiloLog.i("Permission page onPermissionsGranted, code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(
                OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_SYSTEM_AGREE,
                Manifest.permission.READ_SMS)

            sOkiloPermCallback(isGranted = true)
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        OkiloLog.i("onPermissionsDenied code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_SYSTEM_DENY, Manifest.permission.READ_SMS)
            OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS,-1)
            sOkiloPermCallback(isGranted = false)

            //是否是广告渠道
//            val isAdSource = OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_IS_ADSOURCE)
//            if (isAdSource){//广告渠道，拒绝后引导去设置里打开
//                // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
//                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//                    AppSettingsDialog.Builder(this)
//                        .build().show()
//                }
//            } else {//非广告渠道，拒绝后依然进入下一步
//                pushIntentPage()
//            }
        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        OkiloLog.i("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        OkiloLog.i("onRationaleDenied, code: $requestCode")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE){
            // 判断权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(this, Manifest.permission.READ_SMS)
            if (hasPermissions){
                addEventPointRequestAction(
                    OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_SYSTEM_AGREE,
                    Manifest.permission.READ_SMS)

                sOkiloPermCallback(isGranted = true)
            }
        }
    }

    /**
     * 加载权限列表
     */
    private fun gOkiloPermDataList(){
        val permissionList = arrayListOf<JSONObject>()
        val item1 = OkiloPermHp.gOkiloPermSItem()
        permissionList.add(item1)

        val item2 = OkiloPermHp.gOkiloPermPSItem()
        permissionList.add(item2)

        val item3 = OkiloPermHp.gOkiloPermALItem()
        permissionList.add(item3)

        val item4 = OkiloPermHp.gOkiloPermCItem()
        permissionList.add(item4)

        val item5 = OkiloPermHp.gOkiloPermABItem()
        permissionList.add(item5)

        val item6 = OkiloPermHp.gOkiloPermADBItem()
        permissionList.add(item6)

        val item7 = OkiloPermHp.gOkiloPermSTItem()
        permissionList.add(item7)

        okiloPermApt?.data = permissionList
        binding.okiloPermLayout.visibility = View.VISIBLE
    }

    /**
     * 提示dialog
     */
    private fun sOkiloPermReasonDialog(){
        val requestPermission = Manifest.permission.READ_SMS
        val dialog =
            OkiloTipsDlog(this, requestPermission, object : OkiloTipsDlog.IOkiloTipsClickCallback {
                override fun onClick(view: View?) {
                    when (view?.id) {
                        R.id.okiloTipsConfirm -> {
                            gOkiloPermAction()
                        }

                        R.id.okiloTipsCancel -> {
                            addEventPointRequestAction(
                                OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_REASON_DIALOG_DENY,
                                requestPermission
                            )
                        }
                    }
                }
            })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.sOkiloDlogTipsIconResource(R.mipmap.okilo_dlog_tips_icon)
        dialog.sOkiloDlogTipsTitleText(getString(R.string.okilo_dlog_tips),getColor(R.color.okilo_color_ff222222))
        dialog.sOkiloDlogTipsMsgText(getString(R.string.okilo_perm_dlog_agree_tips))
        dialog.sOkiloDlogTipsMsgGravity(Gravity.CENTER)
        dialog.iOkiloDlogTipsDoubleButton(true)
        dialog.sOkiloDlogTipsButtonCancelText(getString(R.string.okilo_btn_cancel))
        dialog.sOkiloDlogTipsButtonConfirmText(getString(R.string.okilo_btn_ok))
    }

    /**
     * 申请权限
     */
    private fun gOkiloPermAction(){
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS,1)
        binding.okiloPermCheckBox.isChecked = true

        val requestReason = getString(R.string.okilo_perm_s_desc1) + "\n" + getString(R.string.okilo_perm_s_desc2) + "\n" + getString(
            R.string.okilo_perm_s_desc3)
        EasyPermissions.requestPermissions(this@OkiloPermAct, requestReason,PERMISSION_REQUEST_CODE,
            Manifest.permission.READ_SMS)
    }
}